<?
class abiturient_model extends MY_Model
	{
		function __construct()
		{
			parent::__construct();	
			preventCSRF();
			$this->essense = 'abiturient';
		}

		function getAllAbiturient($filtrs = '')
		{
			$this->db->select('id, pFamily, pName, tCity, tDiscipline, pPhone, pAdress');
			if (!empty($filtrs))
				$this->db->where($filtrs);

			$this->db->where('dDeleted', 0);

			$res = $this->db->get('abiturient')->result();
			$res = setKeys($res, 'id');//id объектов = id абитуриентов

			if (!empty($res))
			{
				$cityId = extractFieldFromDataArray($res, 'tCity');//копируем поле tCity со всех абитуриентов
				$city = $this->db->where_in('id', $cityId)->get('city')->result();//вытаскиеваем все совпадения
				$city = setKeys($city, 'id');//id объектов = id абитуриентов
	
				$discId = extractFieldFromDataArray($res, 'tDiscipline');
				$disc = $this->db->where_in('id', $discId)->get('discipline')->result();//вытаскиеваем все совпадения
				$disc = setKeys($disc, 'id');//id объектов = id абитуриентов
	
	
				foreach ($res as $p)
				{
					if (isset($city[$p->tCity])) 
						$res[$p->id]->City =  $city[$p->tCity]->pTitle;//если совпадение значения в обьекте со значением id города
					if (isset($disc[$p->tDiscipline]))
						$res[$p->id]->discipline =  $disc[$p->tDiscipline]->pAbrev;
				}
			}

			return $res;
		}

		function getAbiturById($id)
		{
			$this->db->where('id', $id);
			$res = $this->db->get('abiturient')->row();
			if (!empty($res))
				return $res;
			else
				return false;
		}
		
		function updaterDB($table, $data, $update = false)
		{
			$newData = new stdClass();
		

			$query="SELECT * FROM ".$table." WHERE 1 LIMIT 1";  
			$fieldsSQL =mysql_fetch_array(mysql_query($query), MYSQL_ASSOC);  
			foreach($fieldsSQL as $k=>$v)	$fieldsDB[]=$k; 

			$data = (array) $data;
			$keysData = array_keys($data);

			foreach ($keysData as $key => $val) 	
				if (!in_array($val, $fieldsDB))	unset($keysData[$key]);

			foreach ($keysData as $key => $val) 
				$newData->$val= $data[$val];


			if ($update) $id = $newData->id;
			unset($newData->id);
			

			if ($update)
			{
				$this->db->where('id', $id);
				return $this->db->update($table, $newData);
			}
			else
			{	
				return $this->db->insert($table, $newData);
			}
		}

		function delete($id)
		{
			$this->db->where('id', $id);	
			return $this->db->delete('abiturient');
		}


		public function getDataFromSearch($data)
		{
			$table = 'abiturient';
			$descFamily = 'pFamily';
			$descName = 'pName';

			
			$sql = "SELECT * FROM ".$table." abi WHERE ( ";

			$whereDesc = array();

			foreach ($data as $word)
			{ 
				$whereDesc[] = '('.$descFamily.' LIKE "%'.$word.'%")'; 
			}

			foreach ($data as $word)
			{ 
				$whereDesc[] = '('.$descName.' LIKE "%'.$word.'%")'; 
			}
	
			$whereDesc = join(' OR ', $whereDesc);

			$sql .= ' ('.$whereDesc.' AND (abi.dDeleted = 0) )';

			$sql .= ')';

			$res = $this->db->query($sql)->result();

			foreach ($res as $k => $th)
			{
				foreach ($data as $hl)
				{					
					$res[$k]->pFamily = preg_replace('/('.$hl.')/isu', '<mark>$1</mark>', $res[$k]->pFamily);
					$res[$k]->pName = preg_replace('/('.$hl.')/isu', '<mark>$1</mark>', $res[$k]->pName);
				}
			}

			$res = setKeys($res, 'id');

			if (!empty($res))
			{
				$tDisciplines = extractFieldFromDataArray($res, 'tDiscipline');
				$disc = $this->db->where_in('id', $tDisciplines)->get('discipline')->result();
				$disc = setKeys($disc, 'id');
	
				foreach($res as $p)
				{
					if (isset($disc[$p->tDiscipline]))
						$res[$p->id]->discipline = $disc[$p->tDiscipline]->pName;
				}
			}


			return $res;
		}

/**
	
*/
		function getSendedVacancy($id)
		{
//select sea.*, ee.subj from scores_ege_abiturient sea, exams_ege ee 
// where ee.id = sea.tExam and tAbitur in(select id from abiturient where tUser = 17) and tExam in 
// (select tExam from scores_ege_on_discipline where tDiscipline = 9)  
 
			$this->db->where('tUser', $id);
			$this->db->where('dDeleted', 0);
			$res = $this->db->get('abiturient')->result();
			$res = setKeys($res, 'id');//id объектов = id абитуриентов

			if (!empty($res))
			{
				$discId = extractFieldFromDataArray($res, 'tDiscipline');
				$exams = $this->db->where_in('tDiscipline', $discId)->get('scores_ege_on_discipline')->result();

				$examsId= extractFieldFromDataArray($exams, 'tExam');
				$examNames =  $this->db->where_in('id', $examsId)->get('exams_ege')->result();
				$examNames = setKeys($examNames, 'id');

				$abiturId = extractFieldFromDataArray($res, 'id');
				$myExams = $this->db->where('tAbitur', $abiturId[0])->get('scores_ege_abiturient')->result(); //список всех моих экзаменов
				$myExams = setKeys($myExams, 'tExam'); //список всех экзаменов для моих дисциплин

				$discId = extractFieldFromDataArray($res, 'tDiscipline');
				$disc = $this->db->where_in('id', $discId)->get('discipline')->result();
				$disc = setKeys($disc, 'id');

				foreach ($res as $p)
				{
					if (isset($disc[$p->tDiscipline]))
						$res[$p->id]->discName = $disc[$p->tDiscipline]->pName;

					foreach ($exams as $exam)
					{
						if ($p->tDiscipline == $exam->tDiscipline )
						{
							$res[$p->id]->exam[$exam->id] = $exam;
							$res[$p->id]->exam[$exam->id]->pValue = $myExams[$exam->tExam]->pValue;
							$res[$p->id]->exam[$exam->id]->nameDisc = $examNames[$exam->tExam]->subj;
						}
					}

				}

				// diepr($res);
				return $res;
			}
			else false;
		}


		function balls4Disciplyne()
		{

			if (!empty($res))
			{
				$discId = extractFieldFromDataArray($res, 'tDiscipline');
				$disc = $this->db->where_in('id', $discId)->get('discipline')->result();
				$disc = setKeys($disc, 'id');

				$exams = $this->db->where_in('tDiscipline', $discId)->get('scores_ege_on_discipline')->result();
				$exams = setKeys($exams, 'id');

				$examsId= extractFieldFromDataArray($exams, 'tExam');
				$examNames =  $this->db->where_in('id', $examsId)->get('exams_ege')->result();
				$examNames = setKeys($examNames, 'id');


				foreach ($exams as $p)
				{
					if (isset($examNames[$p->tExam])) 
						$exams[$p->id]->discipline = $examNames[$p->tExam]->subj;
				}

				foreach ($res as $p)
				{
					if (isset($disc[$p->tDiscipline])) 
					{
						$res[$p->id]->discipline =  $disc[$p->tDiscipline]->pName;

						foreach ($exams as $exam)
						{
							if ($p->tDiscipline == $exam->tDiscipline)
								$res[$p->id]->exam[] = $exam; 	
						}

					}	
				}

			}
		}


		function getTableCommission()
		{

		}

		function getAllDisciplines()
		{
			return $this->db->get('discipline')->result();
		}


		function getDisciplines($id = 0)
		{
			if (!$id)
			{
				$this->db->select('id');
				$this->db->select('pName');
			}
			else
			{
				$this->db->where('id', $id);
			}
			$res = $this->db->get('discipline')->row();

			if (!empty($res))
			{
			
				$this->db->where('tDiscipline', $res->id);
				$ege = $this->db->get('scores_ege_on_discipline')->result();//список экзаменов по специальности
				$ege = setKeys($ege, 'id');

				if (!empty($ege))
				{
					$ids = extractFieldFromDataArray($ege, 'tExam');
					$this->db->where_in('id', $ids);
					$exam = $this->db->get('exams_ege')->result();
					$exam = setKeys($exam, 'id');
	
	
						foreach ($ege as $key => $itemExam) 
						{
							$res->exam[$key] = $itemExam;
							$res->exam[$key]->discName = $exam[$itemExam->tExam]->subj;
					}
				}
			}

			return $res;
		}
	/**  
		Проверка на существование пользователя и дисциплины в таблице
	*/
		function checkUserAddenOnDisc($tDisc = 0, $tUser, $id = 0)
		{
			if ($id)
				$this->db->where('id', $id);
			if ($tDisc)
				$this->db->where('tDiscipline', $tDisc);
			$this->db->where('tUser', $tUser);
			$this->db->from('abiturient');
			return $this->db->count_all_results();
		}
	}
